<template>
  <div style="min-height: 76vh">
    <el-form @keyup.enter.native="getData()" :inline="true">
      <el-form-item>
        <select-address
          v-model="params.address_code"
          clearable
          auto-top
          placeholder="地区选择"
          @change="getData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          clearable
          @clear="getData()"
          placeholder="主体名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          placeholder="经营者姓名"
          clearable
          v-model="params.corp_name"
          @clear="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <c-select
          placeholder="企业类型"
          @change="getData()"
          clearable
          :options="enumCompanyType"
          v-model="params['org_class.eq']"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <c-select
          placeholder="级别"
          @change="getData()"
          clearable
          :options="enumCompanyLevel"
          v-model="params['lever_type.eq']"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-upload2" @click="handleUpload()">导入</el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          :loading="exportLoading"
          @click="handleDownload()"
        >
          导出
        </el-button>
        <el-button @click="handleEdit()" icon="el-icon-plus" type="primary">新增主体</el-button>
      </el-form-item>
    </el-form>

    <c-table border v-loading="loading" :columns="tableColumns" :data="tableData">
      <template v-slot:business="scope">
        <div class="text-truncate" :title="scope.row.business_scope">
          {{ scope.row.business_scope }}
        </div>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="tableCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <credit-goods-new
      :visible.sync="newVisible"
      :package-id="packageId"
      :package-name="packageName"
      :form-data="formData"
      @success="getData(params.index)"
    ></credit-goods-new>

    <import-excel
      :visible.sync="dialogImportVisible"
      title="导入主体信息"
      :post-api="postUrl"
      excel-template="/static/files/白名单申请导入模板.xlsx"
      @success="getData(params.index)"
    ></import-excel>
  </div>
</template>

<script>
import { enumCompanyType, enumCompanyLevel } from '@/gov/plugins/enum'
import { queryTrouble } from '@vimi/utils-api'
import { exportExcel } from '@/credit/mixin/taskTableProvinceUnion'

import CreditGoodsNew from './CreditGoodsNew'
import ImportExcel from '@/components/ImportExcel'
import SelectAddress from '@/components/select/SelectAddress'

export default {
  components: {
    CreditGoodsNew,
    SelectAddress,
    ImportExcel,
  },
  props: {
    industrialPackage: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      enumCompanyType,
      enumCompanyLevel,
      postUrl: '',
      dialogImportVisible: false,
      exportLoading: false,

      newVisible: false,
      formData: {},

      // api表
      tableName: 'project_white_list',
      tableId: '',
      params: {
        index: 1,
        size: 15,
        corp_name: '',
        customer_name: '',
        address_code: '',
        main_business: '',
      },
      order: {
        scale: 'desc',
      },
      loading: false,

      // 表格
      tableData: [],
      tableCount: 0,
      tableColumns: [
        {
          attrs: { label: '主体名称', prop: 'customer_name', minWidth: '100px' },
          process: (v, row) => ({
            attrs: { class: 'project-history', attrs: { 'data-history': row.is_history } },
          }),
        },
        { attrs: { label: '地址', prop: 'address', minWidth: '150px' } },
        { attrs: { label: '经营者姓名', prop: 'corp_name', align: 'center' } },
        { attrs: { label: '联系电话', prop: 'mobile_no' } },
        { attrs: { label: '产业环节', prop: 'parent_main_business', align: 'center' } },

        { attrs: { label: '主营业务', prop: 'main_business', align: 'center' } },
        { attrs: { label: '产业规模(万羽、万吨)', prop: 'scale' } },
        { attrs: { label: '推荐单位', prop: 'submit_person_name' } },
        { attrs: { label: '推荐时间', prop: 'create_time' } },
        {
          attrs: { label: '操作', align: 'center' },
          operations: [
            { content: '修改', icon: 'fa fa-edit', event: this.handleEdit },
            {
              content: '删除',
              icon: 'fa fa-trash',
              attrs: { class: 'text-danger py-0 px-2' },
              event: this.handleDelete,
              ifRender: false,
            },
          ],
        },
      ],
    }
  },
  computed: {
    packageId() {
      return this.industrialPackage.industrial_package_id
    },
    packageName() {
      return this.industrialPackage.load_name
    },
  },
  watch: {},
  created() {
    this.postUrl =
      '/api/credit/import/' +
      queryTrouble(
        this.tableName,
        {
          importKey: `${this.tableName}_template`,
          'project_type_id.eq': this.packageId,
        },
        {},
        { dropTable: false }
      )

    this.params['project_type_id.eq'] = this.packageId
    this.params.address_code = this.$utils.getAddressCode()
    this.getData()
  },
  mounted() {},
  methods: {
    fetchData(params) {
      return this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, params, this.order || {})
      )
    },
    async getData(index = 1) {
      this.params.index = index
      this.loading = true
      const [res = {}] = await this.fetchData(this.params)
      const data = res.data || {}
      this.tableData = (data.data || []).map(this.dataAdapter)
      this.tableCount = data.totalCount || 0
      this.loading = false
    },
    dataAdapter(item) {
      item.orgClassLabel = enumCompanyType[item.org_class]
      item.leverLabel = enumCompanyLevel[item.lever_type]
      return item
    },
    onNew() {
      this.formData = {}
      this.newVisible = true
    },
    handleEdit(row) {
      this.formData = row || {}
      this.newVisible = true
    },
    async handleDelete(row) {
      this.$utils
        .msgbox({
          message: `确定删除主体：${row.customer_name}?`,
          type: 'warning',
          beforeClose: () =>
            this.$api.deleteData('credit', this.tableName, row.project_white_list_id),
        })
        .then(res => {
          this.$message.success('删除成功！')
          this.$emit('success', res)
          this.getData()
        })
        .catch(err => {
          if (err.status === 403) {
            this.$message.error(`删除失败！没有权限删除该主体`)
          } else {
            this.$message.error(`删除失败！${err.status}`)
          }
        })
    },

    handleUpload() {
      this.dialogImportVisible = true
    },

    async handleDownload() {
      this.exportLoading = true
      exportExcel({
        filename: '产业包主体',
        tableColumns: this.tableColumns,
        params: this.params,
        dataAdapter: this.dataAdapter,
        fetchData: this.fetchData,
        onLoaded: () => {
          this.exportLoading = false
        },
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>
